//
//  ViewController.m
//  UI15_SandBox_NSFileManager_NSFileHandler
//
//  Created by Scott on 16/3/29.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "ViewController.h"
#import "SandboxHandler.h"
#import "ModelOfContact.h"

@interface ViewController ()

@property (nonatomic, copy) NSString *pathOfString;

@property (nonatomic, copy) NSString *pathOfArray;

@property (nonatomic, copy) NSString *pathOfDic;

@property (nonatomic, copy) NSString *pathOfData;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self handleSandBox];
    
    [self saveFundationObject];
    
    [self saveModelToDisk];
    
    [self readModelFromDisk];

    [self handleFileManager];
    
    [self handleFileHandler];
    
}

#pragma mark - 知识点1: SandBox(沙盒)
/** 详见 SandBoxHandler 类. */
- (void)handleSandBox {
    
    SandboxHandler *sandBox = [SandboxHandler sandBoxHandler];
    NSLog(@"sandBox:%@", sandBox.pathOfAppSandbox);
    NSLog(@"%@", sandBox.pathOfDocuments);
    NSLog(@"%@", sandBox.pathOfCaches);
    NSLog(@"%@", sandBox.pathOfPreferences);
    NSLog(@"%@", sandBox.pathOfTemp);
    NSLog(@"%@", sandBox.pathOfAppBundle);
}


#pragma mark - 知识点2: 简单对象写入/读取 (磁盘)
/** 
 * 简单对象: NSFundation框架中的类.
 *
 * Core API: writeToFile:
 */
- (void)saveFundationObject {
    
    [self saveNSString];
    [self readStringFormDisk];
    
    [self saveArray];
    [self readArrFromDisk];
    
    [self saveDictionary];
    [self readDicFromDisk];
    
    [self saveData];
    [self readDataFromDisk];
}

- (void)saveNSString {
    
    NSString *str = @"Dalian SoftPark #10 Building";
    
    // Core API: writeToFile:
    
    // 文件路径
    self.pathOfString = [SandboxHandler saveInDocumentsWithFileName:@"location.txt"];
    
    [str writeToFile:self.pathOfString atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

- (void)readStringFormDisk {
    
    NSString *str = [NSString stringWithContentsOfFile:self.pathOfString encoding:NSUTF8StringEncoding error:nil];
    
    NSLog(@"string: %@", str);
    
}

- (void)saveArray {
    
    NSArray *arr = @[@"zhansan", @"lisi", @"Tom"];
    
    self.pathOfArray = [SandboxHandler saveInDocumentsWithFileName:@"names.jpg"];
    
    [arr writeToFile:self.pathOfArray atomically:YES];
}

- (void)readArrFromDisk {
    
    // 读取
    // 1. 找到文件路径.
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"names.jpg"];
    
    // 2. 创建Arr对象.
    NSArray *arr = [NSArray arrayWithContentsOfFile:path];
    
    // 3. 输出arr
    NSLog(@"arr:%@f", arr);

}

- (void)saveDictionary {
    
    // 1. 要保存的字典
    NSDictionary *dic = @{@"name":@"zhangsan",
                          @"age" :@"18",
                          @"sex" :@"male"};
    
    // 2. 保存的路径.
    self.pathOfDic = [SandboxHandler saveInDocumentsWithFileName:@"people.plist"];
    
    // 3. 保存.
    [dic writeToFile:self.pathOfDic atomically:YES];
    
}

- (void)readDicFromDisk {
    
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:self.pathOfDic];
    NSLog(@"dic:%@", dic);
    
}

- (void)saveData {
    
    // 数据对象.
    UIImage *image = [UIImage imageNamed:@"1.jpg"];
    

    // API: 函数, 将image对象转化为Data对象.
    NSData *data = UIImageJPEGRepresentation(image, 1);
    
    self.pathOfData = [SandboxHandler saveInDocumentsWithFileName:@"image.jpg"];
    
    [data writeToFile:self.pathOfData atomically:YES];
    
}

- (void)readDataFromDisk {
    
    NSData *data = [NSData dataWithContentsOfFile:self.pathOfData];
    
    UIImage *image = [UIImage imageWithData:data];
    
    NSLog(@"%@", image);
    
    
}

#pragma mark - 知识点3: 复杂对象写入/读取 (磁盘)
/** 对象想进行归档, 必须签订NSCoding协议, 并实现两个协议方法. */
- (void)saveModelToDisk {
    
    ModelOfContact *con1 = [[ModelOfContact alloc] init];
    con1.name = @"Tom";
    con1.age = 18;
   
    

    // 归档
    NSMutableData *mData = [NSMutableData data];
    
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mData];
    
    [archiver encodeObject:con1 forKey:@"model"];
    
    // 完成编码
    [archiver finishEncoding];
    
    
    [mData writeToFile:[SandboxHandler saveInDocumentsWithFileName:@"model.da"] atomically:YES];

}

- (void)readModelFromDisk {
    
    NSData *data = [NSData dataWithContentsOfFile:[SandboxHandler saveInDocumentsWithFileName:@"model.da"]];
    
    // 反归档
    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    
    ModelOfContact *model = [unArchiver decodeObjectForKey:@"model"];
    
    // 完成解码.
    [unArchiver finishDecoding];
    
    NSLog(@"%@, %ld", model.name, model.age);
    
}

#pragma mark - 知识点4: NSFileManager
- (void)handleFileManager {
    
    // 创建对象.
    NSFileManager *manage = [NSFileManager defaultManager];
    
    // 创建文件夹.
    NSString *dir = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Demo"];
    
    [manage createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
    
    // ~/iOS/UI
    NSString *dirForUI = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"iOS/UI"];
    
    [manage createDirectoryAtPath:dirForUI withIntermediateDirectories:YES attributes:nil error:nil];
    
    // 创建一个文件(file)
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"task.txt"];
    
    NSData *data = [@"iphone" dataUsingEncoding:NSUTF8StringEncoding];
    
    [manage createFileAtPath:filePath contents:data attributes:nil];
    
    // 查看文件或者目录的属性
    NSDictionary *dic = [manage attributesOfItemAtPath:filePath error:nil];
    
    NSLog(@"arr:%@", dic);
    
    // 删除缓存文件夹(目录)
    [manage removeItemAtPath:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] error:nil];
    
    // caches文件夹删除之后, 再向里面添加文件.
    [manage createFileAtPath:filePath contents:data attributes:nil];
    NSLog(@"filePath:%@", filePath);
    
    
    // 查看一个目录中含有的内容.
    NSArray *array = [manage contentsOfDirectoryAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] error:nil];
    
    NSLog(@"内容:%@", array);
    
    
    // 查看一个文件中含有的内容.
    NSData *data2 = [manage contentsAtPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"name.txt"]];
    
    NSString *name = [[NSString alloc] initWithData:data2 encoding:NSUTF8StringEncoding];
    NSLog(@"name:%@", name);
    
}

#pragma mark - 知识点5: NSFileHandler
- (void)handleFileHandler {
    
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"name.txt"];
    
    
    // 创建对象
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:filePath];
    
    
    // 获取全部数据.
    //    [handle availableData].bytes; /**< 获取NSData的内容首地址. */
    
    NSUInteger length = [handle availableData].length;
    
    NSLog(@"length:%ld", length);
    
    // 关闭文件.
    [handle closeFile];
    
    
    // 利用NSFileHandle进行字符串拼接.
    NSFileHandle *handle2 = [NSFileHandle fileHandleForWritingAtPath:filePath];
    
    // 指针移到文件的最后.
    [handle2 seekToEndOfFile];
    
    // 添加新的内容.
    [handle2 writeData:[@"iOS" dataUsingEncoding:NSUTF8StringEncoding]];
    
    // 关闭文件.
    [handle2 closeFile];
}


@end
